package cn.js189.uqc.util;

import cn.js189.common.util.Base64Util;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.File;
import java.util.Properties;

public class MailUtil {

	private static final Logger LOGGER = LoggerFactory.getLogger(MailUtil.class);

	private static final String HOST = "173.16.69.33";

	private static final int PORT = 25;

	private static final String USERNAME = "service@js.189.cn";

	private static final String CIPHER = "M$Drl92FGx&v@";

	private static final String SENDER = "中国电信江苏网厅";

	private MailUtil() {
		throw new IllegalStateException("Utility class");
	}


	public static boolean sendMail(String sender, String to, String subject, String content, String fileStr) {
		Properties props = new Properties();
		// 指定SMTP服务器
		props.put("mail.smtp.host", HOST);
		// 指定是否需要SMTP验证
		props.put("mail.smtp.auth", "true");

		System.setProperty("mail.mime.splitlongparameters", "false");

		try {
			Session mailSession = Session.getDefaultInstance(props);
			// 是否在控制台显示debug信息
			mailSession.setDebug(true);
			Message message = new MimeMessage(mailSession);
			String nick =javax.mail.internet.MimeUtility.encodeText(StringUtils.isEmpty(sender) ? SENDER : sender);
			// 发件人
			message.setFrom(new InternetAddress(nick + " <" + USERNAME + ">"));
			// 收件人
			message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
			message.setSubject(MimeUtility.encodeText(subject, MimeUtility.mimeCharset("gb2312"), null));
			BodyPart mbp = new MimeBodyPart();
			mbp.setContent(content, "text/html; charset=utf-8");
			Multipart mm = new MimeMultipart();
			// 添加附件
			File[] files = Base64Util.getFile(fileStr);
			if (null != files && files.length > 0) {
				LOGGER.debug("附件文件个数:{}", files.length);
				for (File file : files) {
					if (null != file && file.length() > 0) {
						LOGGER.debug("附件路径:{}", file.getPath());
						System.setProperty("mail.mime.splitlongparameters", "false");
						MimeBodyPart attachmentBodyPart = new MimeBodyPart();
						DataSource source = new FileDataSource(file);
						attachmentBodyPart.setDataHandler(new DataHandler(source));
						String fileName = MimeUtility.encodeWord(file.getName(), MimeUtility.mimeCharset("gb2312"), null);
						LOGGER.debug("附件文件名:{}", fileName);
						attachmentBodyPart.setFileName(fileName);
						mm.addBodyPart(attachmentBodyPart);
					}
				}
			}
			// 将BodyPart加入到MimeMultipart对象中(可以加入多个BodyPart)
			mm.addBodyPart(mbp);
			// 把mm作为消息对象的内容
			message.setContent(mm);
			message.saveChanges();
			Transport transport = mailSession.getTransport("smtp");
			try {
				transport.connect(HOST, PORT, USERNAME, CIPHER);
				transport.sendMessage(message, message.getAllRecipients());
				return true;
			} finally {
				if (transport != null) {
					transport.close();
				}
			}
		} catch (Exception ex) {
			LOGGER.error("发送邮件失败：{}",ex.getMessage());
			return false;
		}
	}

}
